package com.molink.earscope;

import android.app.Activity;
import android.content.Intent;
import android.util.Base64;
import android.util.Log;

import com.wifiview.activity.MainActivity;

import com.alibaba.fastjson.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import io.dcloud.feature.uniapp.annotation.UniJSMethod;
import io.dcloud.feature.uniapp.bridge.UniJSCallback;
import io.dcloud.feature.uniapp.common.UniModule;

public class TestCamera extends UniModule {
    private static final String TAG = "TestCamera";
    public static int REQUEST_CODE = 1000;
    private UniJSCallback back;

    //run ui thread
    @UniJSMethod(uiThread = true)
    public void takePhoto(JSONObject options, UniJSCallback callback) {
        try {
            Log.e(TAG, "takePhoto--" + options);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (callback != null) {
            this.back = callback;
            if (mUniSDKInstance != null && mUniSDKInstance.getContext() instanceof Activity) {
                Intent intent = new Intent(mUniSDKInstance.getContext(), MainActivity.class);
                ((Activity) mUniSDKInstance.getContext()).startActivityForResult(intent, REQUEST_CODE);
            }
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE && data.hasExtra("url")) {
            String url = data.getStringExtra("url");
            String base64 = convertFileToBase64(new File(url));
            Log.e("TestCamera", "原生页面返回----" + base64);

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", "success");
            jsonObject.put("base64",base64 );
            back.invoke(jsonObject);
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    public static String convertFileToBase64(File file) {
        try (FileInputStream imageInFile = new FileInputStream(file)) {
            byte imageData[] = new byte[(int) file.length()];
            imageInFile.read(imageData);
            String imageDataString = Base64.encodeToString(imageData, Base64.DEFAULT);
            return "data:image/jpeg;base64," + imageDataString;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

}
